<template>
  <div>
    <el-card class="box-card">
      <el-button
          type="primary"
          size="default"
          icon="Plus"
          style="color: #e6f1fe; background-color: #16b777; border-color: #16b777"
          @click="addTradeMarkHandler"
      >
        添加品牌
      </el-button>
      <el-table style="margin: 10px 0px" border :data="tradeMarkData">
        <el-table-column
            label="序号"
            type="index"
            width="80px"
            align="center"
        />
        <el-table-column label="品牌名称" prop="tmName" align="center">
          <template #="{ row }">
            <pre>{{ row.tmName }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="品牌LOGO" prop="logoUrl" align="center">
          <template #="{ row }">
            <img :src="row.logoUrl" alt="" style="width: 40px; height: 30px"/>
          </template>
        </el-table-column>
        <el-table-column label="品牌操作" align="center">
          <template #="{ row, $index }">
            <el-button
                type="success"
                class="button-view"
                link
                icon="View"
                @click=""
            >
              查看
            </el-button>
            <el-button
                type="success"
                class="button-view"
                link
                icon="EditPen"
                @click="editTradeMarkHandler(row)"
            >
              编辑
            </el-button>
            <el-button
                type="success"
                class="button-view"
                link
                icon="Delete"
                @click="deleteTradeMarkHandler(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="->, total, sizes,prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="getTrademark"
      />
    </el-card>

    <el-dialog v-model="dialogFormVisible" :title="title">
      <el-form
          style="width: 80%"
          :model="trademarkParams"
          :rules="rules"
          ref="formRef"
      >
        <el-form-item label="品牌名称：" prop="tmName">
          <el-input
              placeholder="请输入品牌名称"
              style="margin-left: 5px"
              v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌Logo：" prop="logoUrl">
          <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img
                v-if="trademarkParams.logoUrl"
                :src="trademarkParams.logoUrl"
                class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="cancelHandler">取消</el-button>
          <el-button type="primary" @click="confirmHandler">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, reactive, nextTick} from 'vue'
import {
  reqGetTrademarkData,
  reqAddOrUpdateTrademarkData,
  reqDeleteTrademarkData,
} from '@/api/product/trademark'
import type {
  TradeMarkResponseData,
  Records,
  TradeMark,
} from '@/api/product/trademark/type'
import type {UploadProps} from 'element-plus'
import {ElMessage, ElMessageBox} from 'element-plus'
//当前页
let currentPage = ref<number>(1)
//每页大小
let pageSize = ref<number>(10)
let small = ref<boolean>(false)
let background = ref<boolean>(false)
const disabled = ref<boolean>(false)
let total = ref<number>(0)
//存储已有品牌的数据
let tradeMarkData = ref<Records>([])
const dialogFormVisible = ref(false)
const title = ref('')
let formRef = ref()
//定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})

const getTrademark = async (pager = 1) => {
  currentPage.value = pager
  console.log('pager = ', pager)
  let result: TradeMarkResponseData = await reqGetTrademarkData(
      currentPage.value,
      pageSize.value,
  )
  console.log('result = ', result)

  if (result.code == 200) {
    total.value = result.data.total
    tradeMarkData.value = result.data.records
  }
}
onMounted(() => {
  getTrademark()
})
//当下拉菜单发生变化的时候触达次方法
//这个自定义时间，分页器组件会将下拉菜单选中数据返回
const handleSizeChange = (val: number) => {
  //当前每一页的数据量发生变化的时候，当前页码归1
  getTrademark()
}
//编辑品牌按钮
const editTradeMarkHandler = (row) => {
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  dialogFormVisible.value = true
  title.value = '编辑品牌'
  console.log('row value = ', row)

  Object.assign(trademarkParams, row)
}
//添加品牌
const addTradeMarkHandler = () => {
  dialogFormVisible.value = true
  title.value = '添加品牌'
  //清空收集数据
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
//上传之前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
      rawFile.type == 'image/png' ||
      rawFile.type == 'image/jpeg' ||
      rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必PNG|JPG|GIF',
    })
    return false
  }
}
//上传成功之后
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile,
) => {
  //response:即为当前这次上传图片post请求服务器返回的数据
  //收集上传图片的地址,添加一个新的品牌的时候带给服务器
  trademarkParams.logoUrl = response.data
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}
//确定上传按钮
const confirmHandler = async () => {
  let result = await reqAddOrUpdateTrademarkData(trademarkParams)
  if (result.code == 200) {
    //关闭对话框
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    //再次发请求获取已有全部的品牌数据
    getTrademark(trademarkParams.id ? currentPage.value : 1)
  } else {
    //添加品牌失败
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
    //关闭对话框
    dialogFormVisible.value = false
  }
}
//取消上传按钮
const cancelHandler = () => {
  dialogFormVisible.value = false
}
//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length > 2) {
    callBack()
  } else {
    //校验未通过返回错误的提示信息
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
//品牌logo图片自定义检验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  //如果图片上传
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}
//表单校验规则
const rules = {
  tmName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorLogoUrl,
    },
  ],
}
//删除指定品牌
const deleteTradeMarkHandler = (row) => {
  console.log('row = ', row)
  ElMessageBox.confirm('确定要删除：' + row.tmName,
      '注意',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    let result: any = reqDeleteTrademarkData(row.id);
    if (result.code = 200) {
      ElMessage({
        type: 'success',
        message: '成功删除!',
      })
      //在查询当前的页码
      getTrademark(tradeMarkData.value.length > 1 ? currentPage.value : currentPage.value - 1)
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!',
    })
  })
}
</script>

<style scoped lang="scss">
.button-view {
  color: #16b777;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
